﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 28/06/2011
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Dictionary)]
    public class VideoCategoryController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        //
        // GET: /VideoCategory/

        public ActionResult Index(int? page)
        {
            try
            {
                    if (!page.HasValue)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("videoCategory.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("videoCategory.orderDir", "orderDir", "desc").ToString();
                    string keyword = UserState.getUserStateFromRequest("videoCategory.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("videoCategory.pageSize", "PageSize", 20).ToString());
                    string strPub = UserState.getUserStateFromRequest("videoCategory.CurrentPubStatus", "CurrentPubStatus", "").ToString();

                    int? CurrentPubStatus = null;
                    if (!string.IsNullOrEmpty(strPub))
                        CurrentPubStatus = Convert.ToInt32(strPub);

                    var categories = eDataContext.VideoCategories
                        .Where(c => CurrentPubStatus.HasValue ? c.ActiveYN == (CurrentPubStatus.HasValue && CurrentPubStatus.Value == 1 ? true : false) : true)
                        .Where(c => (string.IsNullOrEmpty(keyword) ? true : c.Name.ToLower().Contains(keyword.ToLower().Trim())
                        ))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new VideoCategoryViewModels
                    {
                        Categories = categories,
                        CurrentPubStatus = CurrentPubStatus,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /VideoCategory/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                    VideoCategory videoC = eDataContext.VideoCategories.Where(v => v.ID == id).FirstOrDefault();

                    string pName = videoC.ParentID.HasValue ?
                        eDataContext.VideoCategories.Where(v => v.ID == videoC.ParentID.Value).FirstOrDefault().Name :
                        string.Empty;

                    return View(new VideoCategoryInputModels
                    {
                        Category = videoC,
                        ParentCatName = pName
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /VideoCategory/Create

        public ActionResult Create()
        {
            try
            {
                    List<TreeNodeItem> listTree = eDataContext.VideoCategories
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    return View(new VideoCategoryInputModels
                    {
                        ListParentCategories = categories
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /VideoCategory/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(VideoCategoryInputModels m)
        {
            try
            {
                    UpdateModel(m.Category);
                    m.Category.ModifyBy = UserManager.GetUserId();
                    m.Category.AddDate = DateTime.Now;
                    m.Category.ModifyDate = DateTime.Now;
                    m.Category.ModifyBy = UserManager.GetUserId();
                    eDataContext.VideoCategories.InsertOnSubmit(m.Category);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /VideoCategory/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                    VideoCategory videoC = eDataContext.VideoCategories.Where(v => v.ID == id).FirstOrDefault();

                    List<TreeNodeItem> listTree = eDataContext.VideoCategories
                                                    .Where(c => c.ID != videoC.ID)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = videoC.ParentID.HasValue ?
                        new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, videoC.ParentID.Value) :
                        new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    return View(new VideoCategoryInputModels
                    {
                        ListParentCategories = categories,
                        Category = videoC
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /VideoCategory/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, VideoCategoryInputModels m)
        {
            try
            {
                    m.Category = eDataContext.VideoCategories.Where(v => v.ID == id).FirstOrDefault();
                    UpdateModel(m.Category);
                    m.Category.ModifyBy = UserManager.GetUserId();
                    m.Category.AddDate = DateTime.Now;
                    m.Category.ModifyDate = DateTime.Now;
                    m.Category.ModifyBy = UserManager.GetUserId();
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Article/Delete/5

        public ActionResult Delete(int id)
        {
            try
            {
                    int nItem = eDataContext.VideoCategories.Where(d => d.ParentID.HasValue && d.ParentID.Value == id).Count();
                    if (nItem > 0)
                        throw new Exception("Chuyên mục bạn xoá là chuyên mục cha. Bạn phải xoá chuyên mục con trước.");

                    VideoCategory formDoc = eDataContext.VideoCategories.Where(f => f.ID == id).FirstOrDefault();

                    return View(formDoc);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Article/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    VideoCategory formDoc = eDataContext.VideoCategories.Where(f => f.ID == id).FirstOrDefault();
                    if (formDoc != null)
                    {
                        eDataContext.VideoCategories.DeleteOnSubmit(formDoc);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
